<template>
  <el-dialog
    title="发表评论"
    :visible.sync="visible"
    width="600px"
    :before-close="handleClose"
    class="comment-dialog"
  >
    <el-form :model="commentForm" :rules="commentRules" ref="commentForm" label-width="80px">
      <!-- 评分 -->
      <el-form-item label="评分" prop="rating">
        <div class="rating-section">
          <el-rate
            v-model="commentForm.rating"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            show-text
            :texts="['很差', '较差', '一般', '不错', '很好']"
            size="large"
          ></el-rate>
        </div>
      </el-form-item>

      <!-- 评论内容 -->
      <el-form-item label="评论" prop="content">
        <el-input
          type="textarea"
          v-model="commentForm.content"
          :rows="6"
          placeholder="请分享您的使用体验..."
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="图片">
        <el-upload
          ref="commentImageUpload"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleImageRemove"
          :on-success="handleImageSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeImageUpload"
          :file-list="imageList"
          list-type="picture-card"
          :limit="6"
          accept="image/*"
          name="files"
          class="comment-upload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="upload-tip">最多上传6张图片，每张不超过5MB</div>
        
        <!-- 图片预览对话框 -->
        <el-dialog :visible.sync="dialogVisible" title="图片预览">
          <img style="width: 100%" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitComment" :loading="submitting">
        <i class="el-icon-s-promotion"></i>
        发表评论
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "CommentDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    goodsId: {
      type: [String, Number],
      required: true
    },
    currentUserId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      submitting: false,
      
      // 评论表单
      commentForm: {
        rating: 5,
        content: "",
        images: []
      },
      
      // 表单验证规则
      commentRules: {
        rating: [
          { required: true, message: "请选择评分", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入评论内容", trigger: "blur" },
          { min: 5, max: 500, message: "评论内容长度在 5 到 500 个字符", trigger: "blur" }
        ]
      },
      
      // 图片上传
      imageList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: 'http://localhost:8079/admin/product/multiUpload' // 图片上传接口
    };
  },
  computed: {
    uploadHeaders() {
      return {
        'Authorization': `Bearer ${this.$store.state.user.token}`
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm();
      }
    }
  },
  methods: {
    // 提交评论
    submitComment() {
      this.$refs.commentForm.validate(valid => {
        if (!valid) return;
        
        this.submitting = true;
        
        const commentData = {
          goodsId: parseInt(this.goodsId),
          userId: parseInt(this.currentUserId),
          username: this.$store.state.user.username || "匿名用户",
          userAvatar: this.$store.state.user.avatar || "",
          content: this.commentForm.content,
          rating: this.commentForm.rating,
          images: this.imageList.length > 0 ? JSON.stringify(this.imageList.map(img => img.url)) : "",
          parentId: 0
        };

        this.$axios
          .post("/comment/add", commentData)
          .then(resp => {
            if (resp && resp.status === 200) {
              this.$message.success("评论发表成功");
              this.handleClose();
              this.$emit("comment-added");
            } else {
              this.$message.error("评论发表失败");
            }
          })
          .catch(error => {
            console.error("发表评论失败:", error);
            this.$message.error("评论发表失败");
          })
          .finally(() => {
            this.submitting = false;
          });
      });
    },

    // 重置表单
    resetForm() {
      this.commentForm = {
        rating: 5,
        content: "",
        images: []
      };
      this.imageList = [];
      this.$nextTick(() => {
        if (this.$refs.commentForm) {
          this.$refs.commentForm.resetFields();
        }
      });
    },

    // 图片上传成功
    handleImageSuccess(response, file, fileList) {
      console.log('图片上传成功:', response);
      if (response.code === 200 && response.data && response.data.length > 0) {
        // 后端返回的是URL数组，取第一个作为当前图片URL
        file.url = response.data[0];
        this.imageList = fileList;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.message || '图片上传失败');
        // 从文件列表中移除失败的文件
        this.imageList = fileList.filter(item => item.uid !== file.uid);
      }
    },

    // 图片上传失败
    handleUploadError(error, file, fileList) {
      console.error('图片上传失败:', error);
      this.$message.error('图片上传失败，请重试');
      // 从文件列表中移除失败的文件
      this.imageList = fileList.filter(item => item.uid !== file.uid);
    },

    // 图片上传前验证
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isImage) {
        this.$message.error('只能上传图片格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },

    // 处理图片移除
    handleImageRemove(file, fileList) {
      this.imageList = fileList;
    },

    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 关闭弹窗
    handleClose() {
      this.resetForm();
      this.$emit("update:visible", false);
    }
  }
};
</script>

<style scoped>
.comment-dialog {
  border-radius: 12px;
}

.comment-dialog :deep(.el-dialog__header) {
  background: #00caa8;
  color: white;
  border-radius: 12px 12px 0 0;
}

.comment-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.comment-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.comment-dialog :deep(.el-dialog__body) {
  padding: 30px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.comment-upload {
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
  padding: 20px 30px;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer .el-button {
  padding: 12px 24px;
  font-size: 14px;
  border-radius: 8px;
}

.dialog-footer .el-button--primary {
  background: #00caa8;
  border: none;
}

.dialog-footer .el-button--primary:hover {
  background: #00b894;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 202, 168, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }
  
  .comment-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .dialog-footer {
    padding: 15px 20px;
  }
}
</style> 